package org.edu.modules.act.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.system.vo.LoginUser;
import org.edu.modules.act.common.result.ActionResult;
import org.edu.modules.act.common.result.ListResult;
import org.edu.modules.act.common.result.ResultBuilder;
import org.edu.modules.act.entity.ActReWordModel;
import org.edu.modules.act.entity.ActRuInstanceFileEntity;
import org.edu.modules.act.entity.Leave;
import org.edu.modules.act.mapper.ActRuInstanceFileMapper;
import org.edu.modules.act.service.ProcessService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.processing.ProcessingEnvironment;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 流程信息的控制层
 *
 * @版权所有 福州土著人信息科技有限公司
 */
@Api(tags="流程定义模块模块")
@RestController
@RequestMapping("/activiti/process")
public class ProcessController {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ProcessService processService;

	@Resource
	private ActRuInstanceFileMapper actRuInstanceFileMapper;

	/**
	 * 查询流程定义分页
	 *
	 * @param current           当前页数
	 * @param pageSize              每页记录数
	 * @param processDefinitionName 流程定义名称
	 * @return
	 */
	@ApiOperation(value="查询流程定义分页", notes="流程设计模块-查询流程定义分页")
	@GetMapping(path = "/queryProcessDefinition")
	public Result<?> queryProcessDefinition(@RequestParam(name = "current", required = false, defaultValue = "1") Integer current,
			@RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize,
			@RequestParam(name = "processDefinitionName", required = false) String processDefinitionName) {
			Map<String, Object> data = processService.queryProcessDefinition(current, pageSize, processDefinitionName);
		return Result.OK(data);
	}

	/**
	 * 查询流程实例分页
	 *
	 * @param current         当前页数
	 * @param pageSize            每页记录数
	 * @param processInstanceName 流程实例名称
	 * @return
	 */
	@ApiOperation(value="查询流程实例分页", notes="流程设计模块-查询流程实例分页")
	@GetMapping(path = "/queryProcessInstance")
	public Result<?> queryProcessInstance(Integer current,Integer pageSize,String processInstanceName) {
		Map<String, Object> data = processService.queryProcessInstance(current, pageSize, processInstanceName);
		return Result.OK(data);
	}

	/**
	 * 查询流程实例执行路径分页
	 *
	 * @param current       当前页数
	 * @param pageSize          每页记录数
	 * @param processInstanceId 流程实例ID
	 * @return
	 */
	@ApiOperation(value="查询流程实例执行路径分页", notes="流程设计模块-查询流程实例执行路径分页")
	@GetMapping(path = "/queryExecution")
	public Result<?> queryExecution(Integer current,Integer pageSize,String processInstanceId) {
		Map<String, Object> data = processService.queryExecution(current, pageSize, processInstanceId);
		return Result.OK(data);
	}

	/**
	 * 获取流程定义XML
	 *
	 * @param deploymentId 部署ID
	 * @return
	 */
	@ApiOperation(value="获取流程定义XML", notes="流程设计模块-获取流程定义XML")
	@PostMapping(path = "/getProcessResource")
	public ListResult<Object> getProcessResource(String deploymentId) {
		return ResultBuilder.buildListSuccess(processService.getProcessResource(deploymentId));
	}

	/**
	 * 获取高亮跟踪流程图
	 *
	 * @param processInstanceId 流程实例ID
	 * @return
	 */
	@ApiOperation(value="获取高亮跟踪流程图", notes="流程设计模块-获取高亮跟踪流程图")
	@PostMapping(path = "/getHighLightedProcessDiagram")
	public ListResult<Object> getHighLightedProcessDiagram(String processInstanceId) {
		System.out.println(processInstanceId+"***************------");
		return ResultBuilder.buildListSuccess(processService.getHighLightedProcessDiagram(processInstanceId));
	}

	/**
	 * 获取流程定义图片
	 *
	 * @param deploymentId 部署ID
	 * @return
	 */
	@ApiOperation(value="获取流程定义图片", notes="流程设计模块-获取流程定义图片")
	@PostMapping(value = "/getProcessImage")
	public ResponseEntity<byte[]> getProcessImage(String deploymentId) {
		ResponseEntity<byte[]> responseEntity = null;
		try {
			InputStream imageInputStream = processService.getProcessImage(deploymentId);
			HttpHeaders responseHeaders = new HttpHeaders();
			responseHeaders.set("Content-Type", "text/xml");
			responseEntity = new ResponseEntity<>(IOUtils.toByteArray(imageInputStream), responseHeaders, HttpStatus.OK);
		} catch (IOException e) {
			logger.warn(e.toString());
		}
		return responseEntity;
	}

	/**
	 * 持久化流程
	 *
	 * @param modelId 模型ID
	 * @param jsonXml 流程基本信息
	 * @param svgXml  流程设计信息
	 * @throws Exception
	 */
	@ApiOperation(value="持久化流程", notes="流程设计模块-持久化流程")
	@PostMapping(path = "/persistProcess")
	public ActionResult persistProcess(String modelId,String jsonXml,String svgXml) {
		processService.persistProcess(modelId, jsonXml, svgXml);
		return ResultBuilder.buildActionSuccess();
	}

	/**
	 * 发起流程
	 *
	 * @param leave 请假对象
	 * @return
	 */
	@ApiOperation(value="发起流程", notes="流程设计模块-发起流程")
	@PostMapping(path = "/startProcessInstance")
	public ActionResult startProcessInstance(Leave leave,String wordText,String fileId) {
		System.out.println(leave.getProcessDefinitionId());
		System.out.println(wordText+"*****************文件h5");

		//获取redis缓存的用户ID
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//根据FileId获取集合
		QueryWrapper<ActRuInstanceFileEntity> wrapper = new QueryWrapper();
		wrapper.eq("ID",fileId);
		//获取集合
		List<ActRuInstanceFileEntity> list = actRuInstanceFileMapper.selectList(wrapper);
		if(list.size()==0){
			System.out.println("这里集合长度为0，插入数据");
			ActRuInstanceFileEntity actRuInstanceFileEntity=new ActRuInstanceFileEntity();
			actRuInstanceFileEntity.setWordFileUrl(wordText);
			actRuInstanceFileEntity.setUserId(user.getId());
			actRuInstanceFileEntity.setTerminalId(1);
			String uuid= UUID.randomUUID().toString();
			actRuInstanceFileEntity.setProcInstId(uuid);
			//插入数据
			actRuInstanceFileMapper.insert(actRuInstanceFileEntity);
			//查询刚才插入的ID
			wrapper = new QueryWrapper();
			wrapper.eq("PROC_INST_ID",uuid);
			list=actRuInstanceFileMapper.selectList(wrapper);
			fileId=list.get(0).getId().toString();
			System.out.println("新的FileID"+fileId);
		}else{
			//根据ID修改word表的word文件字段
			ActRuInstanceFileEntity actRuInstanceFileEntity=new ActRuInstanceFileEntity();
			actRuInstanceFileEntity.setWordFileUrl(wordText);
			Long id=Long.parseLong(fileId);
			actRuInstanceFileEntity.setId(id);
			//修改表
			actRuInstanceFileMapper.updateById(actRuInstanceFileEntity);
		}

		processService.startProcessInstance(leave, user.getId(),user.getRealname(),fileId);
		return ResultBuilder.buildActionSuccess();
	}

	/**
	 * 挂起流程定义
	 *
	 * @param processDefinitionId 流程定义ID
	 * @return
	 */
	@ApiOperation(value="挂起流程定义", notes="流程设计模块-挂起流程定义")
	@PostMapping(path = "/suspendProcessDefinition")
	public ActionResult suspendProcessDefinition(String processDefinitionId) {
		processService.suspendProcessDefinition(processDefinitionId);
		return ResultBuilder.buildActionSuccess();
	}

	/**
	 * 激活流程定义
	 *
	 * @param processDefinitionId 流程定义ID
	 * @return
	 */
	@ApiOperation(value="激活流程定义", notes="流程设计模块-激活流程定义")
	@PostMapping(path = "/activateProcessDefinition")
	public ActionResult activateProcessDefinition(String processDefinitionId) {
		processService.activateProcessDefinition(processDefinitionId);
		return ResultBuilder.buildActionSuccess();
	}

	/**
	 * 挂起流程实例
	 *
	 * @param processInstanceId 流程实例ID
	 * @return
	 */
	@ApiOperation(value="挂起流程实例", notes="流程设计模块-挂起流程实例")
	@PostMapping(path = "/suspendProcessInstance")
	public ActionResult suspendProcessInstance(String processInstanceId) {
		processService.suspendProcessInstance(processInstanceId);
		return ResultBuilder.buildActionSuccess();
	}

	/**
	 * 激活流程实例
	 *
	 * @param processInstanceId 流程实例ID
	 * @return
	 */
	@ApiOperation(value="激活流程实例", notes="流程设计模块-激活流程实例")
	@PostMapping(path = "/activateProcessInstance")
	public ActionResult activateProcessInstance(String processInstanceId) {
		processService.activateProcessInstance(processInstanceId);
		return ResultBuilder.buildActionSuccess();
	}

	/**
	 * 删除流程实例
	 *
	 * @param processInstanceId 流程实例ID
	 * @return
	 */
	@ApiOperation(value="删除流程实例", notes="流程设计模块-删除流程实例")
	@PostMapping(path = "/deleteProcessInstance")
	public ActionResult deleteProcessInstance(String processInstanceId) {
		processService.deleteProcessInstance(processInstanceId);
		return ResultBuilder.buildActionSuccess();
	}

	/**
	 * 上传流程表单文件
	 *
	 * @param file       文件资源
	 * @param processInstanceId         流程id
	 * @param processInstanceKey         流程key
	 * @return
	 * @throws Exception
	 */
//	@ApiOperation(value="上传流程表单文件", notes="流程设计模块-上传流程表单文件")
//	@PostMapping(value = "/uploadProcessTemplaterFile", consumes = { "multipart/form-data" })
//	public ListResult<Object> uploadFile(MultipartFile file,String processInstanceId,String processInstanceKey) throws Exception {
//		String url = processService.uploadFile(file, processInstanceId, processInstanceKey);
//		return ResultBuilder.buildListSuccess(url);
//	}

}
